<!--
 * @Description: 新增深化设计策划书
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-08-18 15:53:25
 * @LastEditTime: 2022-12-07 20:01:52
 * @FilePath: \cscec-pms-admin\src\views\design\deepDesign\planningManagement\form.vue
-->
<template>
  <!-- 新增深化设计策划书 -->
  <base-breadcrumb
    class="flexMemberInfo-container"
    :title="title[page.pageType] +'深化设计策划书'"
    :breadcrumb="!isAudit"
  >
    <a-spin :spinning="loading">
      <a-card>
        <title-name :title="title[page.pageType]?title[page.pageType]+'深化设计策划书':form.name" />
        <!-- 表单 -->
        <custom-form
          ref="form"
          :is-validate="true"
          :edit-model="''"
          :rules="rules"
          :form="form"
          :form-list="formOption"
          :is-emit="false"
          @selectOrg="selectOrg"
        >
          <template slot="deepen">
            <a-checkbox-group
              v-model="form.deepen"
              name="checkboxgroup"
              :options="deepList"
              :disabled="!page.pageType ||isDetail"
            />
          </template>
          <template slot="designType">
            <BaseInput
              v-model="form.designType"
              disabled
            />
          </template>
        </custom-form>
        <!-- 表单 -->
      </a-card>
      <a-card>
        <title-name :title="!page.pageType?'深化设计策划书/盈亏分析表':'上传深化设计策划书/盈亏分析表'" />
        <UploadTableNew
          ref="uploadTable"
          :disabled="!page.pageType || isDetail"
          :mode="file.mode"
          :init-file-list="file.fileList"
          :need-page="file.needPage"
          :business-code="file.businessCode"
          :use-multi-delete="file.useMultiDelete"
          :use-multi-export="file.useMultiExport"
        />
      </a-card>
      <div v-if="!isConsultation" class="tool-btns page-btn-right-top">
        <a-button
          v-if="page.pageType && !isDetail"
          class="ml20"
          :loading="submitLoading"
          type="primary"
          @click="handleSubmit('0')"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="page.pageType && !isDetail"
          class="ml20"
          :loading="submitLoading"
          type="primary"
          @click="handleSubmit('1')"
        >
          提交
        </a-button>
        <a-button
          class="ml20"
          @click="handleClose"
        >
          关闭
        </a-button>
      </div>
    </a-spin>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
  <!-- 新增深化设计策划书 -->
</template>
<script>
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import { deepList } from './model.js'
import { getAuditProject } from '@/api/themeChoose/themeChoose'
import planningManagement from '@/api/design/deepDesign/planningManagement'
import Moment from 'moment'
import cloneDeep from 'lodash.clonedeep'
export default {
  name: 'PlanningManagementAdd',
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  components: {},
  data() {
    return {
      // 页面加载
      loading: false,
      // 标题
      title: {
        add: '新增',
        detail: '查看',
        update: '编辑'
      },
      // 表单
      form: {
        branchCompanyId: '',
        branchCompany: '',
        projectId: '',
        project: '',
        designType: '',
        name: '',
        time: '',
        person: '',
        fileIds: [],
        deepen: []
      },
      // 深化项列表
      deepList,
      // 相关资料
      file: {
        // 处理操作的模式：'add'模式下，删除操作会调用文件删除接口，'edit'模式只会在表格中移除删除数据，不会调用接口
        mode: this.$route.query.pageTyp === 'add' ? 'add' : 'edit',
        // 上传文件的业务编码
        businessCode: 'PM32',
        // 是否需要分页
        needPage: false,
        // 初始化文件列表
        fileList: [],
        // 批量删除
        useMultiDelete: true,
        // 批量导出
        useMultiExport: true
      },
      // 提交加载
      submitLoading: false,
      // 项目设计管理类别
      designType: {},
      // 登录人信息
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      // 页面数据
      page: this.$route.query,
       //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    // 查看禁用表单
    isDetail() {
      return this.page.pageType === 'detail'
    },
    // 表单配置
    formOption() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: this.page.pageType === 'add',
          isNeedAuth:true,
          checkStrictly: true,
          disabled: !this.page.pageType || this.isDetail,
          isQueryProjecDetail: false
        },
        // {
        //   label: '分公司',
        //   keyName: 'branchCompanyId',
        //   type: SelectSubCompany,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: this.page.pageType === 'add'
        //   },
        //   selectChange: (e) => {
        //     this.form.branchCompany = e.orgName
        //   },
        //   rules: [{ required: true, message: '请选择', trigger: 'change' }],
        //   disabled: !this.page.pageType || this.isDetail
        // },
        // {
        //   label: '项目名称',
        //   keyName: 'projectId',
        //   type: SelectProject,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: this.page.pageType === 'add',
        //     keyValue: 'branchCompanyId',
        //     isEdit: true,
        //     form: this.form
        //   },
        //   selectChange: (e) => {
        //     this.form.project = e.name
        //     this.form.name = `${e.name}项目深化设计策划书`
        //   },
        //   rules: [{ required: true, message: '请选择', trigger: 'change' }],
        //   disabled: !this.page.pageType || this.isDetail
        // },
        {
          label: '项目设计管理类别',
          keyName: 'designType',
          slot: true,
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          label: '深化设计策划书名称',
          keyName: 'name',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建时间',
          keyName: 'time',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建人',
          keyName: 'person',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '深化项',
          keyName: 'deepen',
          slot: true,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          span: 24
        }
      ]
    },
    // 校验
    rules() {
      const obj = {}
      this.formOption.map((item) => {
        if (item.rules) {
          obj[item.keyName] = item.rules
        }
      })
      console.log(obj)
      return obj
    }
  },
 async mounted() {
    this.form.time = Moment().format('YYYY-MM-DD')
    this.form.person = this.userInfo.name
    if (this.page.pageType === 'update' || this.page.pageType === 'detail' || this.isAudit) {
      this.getDetail()
    }
     //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('deepen_design_plan_book')
  },
  watch: {
    'form.projectId': {
      handler(val) {
        this.getDesignType(val)
      }
    },
    'file.fileList': {
      handler(val) {
        this.form.fileIds = val.map((el) => el.commonId)
      }
    }
  },
  methods: {
    selectOrg(val) {
      this.form.branchCompanyId = val[val.length - 2].orgId
      this.form.branchCompany = val[val.length - 2].orgName
      this.form.project = val[val.length - 1].orgName
      this.form.name = `${val[val.length - 1].orgName}项目深化设计策划书`
    },
    /**
     * @description: 获取项目设计管理类别
     * @param {void}
     * @return {void}
     */
    async getDesignType(val) {
      try {
        const { data } = await getAuditProject({
          projectId: val,
          branchCompanyIds: [this.form.branchCompanyId]
        })
        this.designType = {
          designTypeId: data[0]?.designTypeId || undefined,
          designType: data[0]?.designTypeName || undefined
        }
        this.form.designTypeId = this.designType.designTypeId
        this.form.designType = this.designType.designType
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * @description: 获取深化设计策划书详情
     * @param {void}
     * @return {void}
     */
    async getDetail() {
      this.loading = true
      const { data, code, message } = await planningManagement.detail({ id: this.page.id })
      if (code === 200) {
        Object.keys(this.form).forEach((el) => {
          if (el === 'deepen') {
            console.log(data[el])
            this.form[el] = data[el] === '' ? [] : data[el].split(',')
          } else if (el === 'fileIds') {
            this.form[el] = data.fileIdsInfo || []
            this.file.fileList = data.fileIdsInfo || []
          } else {
            this.form[el] = data[el] || this.form[el]
          }
        })
      } else {
        this.$message.warning(message)
      }
      this.loading = false
    },
    /**
     * @description: 保存草稿，提交
     * @param {string} 状态：草稿0，提交1
     * @return {void}
     */
    handleSubmit(status) {
      this.setProcessConfig = null;
      if (status === '1') {
        // 提交
        console.log(this.form.designType)
        console.log(this.form)
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.form.fileIds && this.form.fileIds.length > 0) {
              this.submitApprovalConfirm(this.processConfig, (flag)=>{
                if(!flag) {
                  return
                }
                this.add(status)
              })
            } else {
              this.$message.warning('请上传深化设计策划书/盈亏分析表')
            }
          }
        })
      } else {
        // 草稿
        this.add(status)
      }
    },
    add(status) {
      this.submitLoading = true
      const form = cloneDeep(this.form)
      form.deepen = this.form.deepen.join(',')
      form.status = status
      if (this.page.pageType === 'update') {
        // 编辑
        form.id = this.page.id
        planningManagement
          .update(form)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success('操作成功')
              if(status*1===1){
                //提交时，返回id
                this.businessId = res.data.id || this.page.id;
                this.setProcessConfig = this.processConfig;
              }else{
                this.handleClose()
              }
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.submitLoading = false
          })
      } else {
        // 新增
        planningManagement
          .add(form)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success('操作成功')
               if(status*1===1){
                //提交时，返回id
                this.businessId = res.data.id || this.page.id;
                this.setProcessConfig = this.processConfig;
              }else{
                this.handleClose()
              }
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.submitLoading = false
          })
      }
    },
    /**
     * @description: 关闭
     * @param {void}
     * @return {void}
     */
    handleClose() {
      this.$multiTab.close(this.$route.fullpath)
    }
  }
}
</script>
<style lang="less" scoped>
</style>
